package org.nightrunner.d3.controller.management;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.nightrunner.d3.constant.CRUDConstant;
import org.nightrunner.d3.entity.Category;
import org.nightrunner.d3.entity.Equipment;
import org.nightrunner.d3.log.SysLog;
import org.nightrunner.d3.model.DefaultPaginationInfo;
import org.nightrunner.d3.model.IPaginationInfo;
import org.nightrunner.d3.model.PaginationModel;
import org.nightrunner.d3.service.ICTEService;
import org.nightrunner.d3.service.ICategoryService;
import org.nightrunner.d3.service.IEquipmentService;
import org.nightrunner.d3.service.ISearchService;
import org.nightrunner.d3.util.OperateInfo;
import org.nightrunner.d3.util.OperateInfo.Link;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonObject;

/**
 * Matter Management Controller
 * 
 * @author haiyang.chen
 * @date 2012-5-15
 * @version 1.0
 */
@Controller
@RequestMapping("/management/equipment/")
public class EquipmentManagementController implements CRUDConstant {

	private static final String RETURN_VIEW_PREFIX = "/management/equipment/";

	public static final Logger LOGGER = SysLog.CONTROLLER;

	@Autowired
	private ICategoryService categoryService;

	@Autowired
	private IEquipmentService equipmentService;

	@Autowired
	private ICTEService CTEService;

	public ICTEService getCTEService() {
		return CTEService;
	}

	public void setCTEService(ICTEService cTEService) {
		CTEService = cTEService;
	}

	public IEquipmentService getEquipmentService() {
		return equipmentService;
	}

	public void setEquipmentService(IEquipmentService matterService) {
		this.equipmentService = matterService;
	}

	public ICategoryService getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(ICategoryService categoryService) {
		this.categoryService = categoryService;
	}

	@RequestMapping(value = "list-{currentPage}-{rowSize}", method = RequestMethod.GET)
	public String list(HttpServletResponse response,
			HttpServletRequest request, ModelMap modelMap,
			@PathVariable("rowSize") Integer rowSize,
			@PathVariable("currentPage") Integer currentPage) {
		IPaginationInfo pagination = new DefaultPaginationInfo();
		pagination.setCurrentPage(currentPage);
		pagination.setRowSize(rowSize);

		PaginationModel<List<Equipment>> paginationModel = equipmentService
				.getEquipments(pagination);
		modelMap.addAttribute("paginationModel", paginationModel);
		return RETURN_VIEW_PREFIX + VIEW_LIST;
	}

	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(HttpServletResponse response,
			HttpServletRequest request, ModelMap modelMap) {
		return list(response, request, modelMap, 10, 0);
	}

	@RequestMapping(value = "", method = RequestMethod.GET)
	public String root(HttpServletResponse response,
			HttpServletRequest request, ModelMap modelMap) {
		return list(response, request, modelMap, 10, 0);
	}

	@RequestMapping(value = "preupdate/{equipmentId}", method = RequestMethod.GET)
	public String preUpdate(HttpServletResponse response,
			HttpServletRequest request, ModelMap modelMap,
			@PathVariable("equipmentId") String equipmentId) {
		try {
			Equipment equipment = equipmentService.getEquipment(equipmentId);

			modelMap.addAttribute("equipment", equipment);

			List<Category> matterCategories = CTEService
					.getCategorys(equipment);

			List<List<Category>> superCategoryChains = new ArrayList<List<Category>>(
					matterCategories.size());

			List<Category> tempEquipmentCategories = null;
			for (Category category : matterCategories) {
				tempEquipmentCategories = categoryService
						.getSuperCategoryChain(category);
				tempEquipmentCategories.add(category);
				superCategoryChains.add(tempEquipmentCategories);
			}
			modelMap.addAttribute("superCategoryChains", superCategoryChains);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return RETURN_VIEW_PREFIX + VIEW_UPDATE;
	}

	private static final String LINK_INDEX = "/management/equipment/list-0-10";

	private static final String LINK_NAME_INDEX = "物品管理首页";

	@RequestMapping(value = "add", method = RequestMethod.POST)
	public String add(HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap) {

		Equipment equipment = new Equipment();
		String equipmentName = request.getParameter("equipmentName");
		String equipmentKeywords = request.getParameter("equipmentKeywords");
		String equipmentItemLevel = request.getParameter("equipmentItemLevel");
		String equipmentDescription = request
				.getParameter("equipmentDescription");

		equipment.setEquipmentName(equipmentName);
		equipment.setEquipmentDescription(equipmentDescription);
		equipment.setEquipmentItemLevel(equipmentItemLevel);
		equipment.setEquipmentKeywords(equipmentKeywords);

		equipmentService.updateEquipment(equipment);

		OperateInfo operateInfo = new OperateInfo();
		operateInfo.setInfo(OPERATE_INFO_UPDATE_OK);
		operateInfo.addLink(new Link(LINK_NAME_INDEX, LINK_INDEX));
		modelMap.addAttribute(REQUEST_KEY_OPERATE_INFO, operateInfo);

		return VIEW_OPERATE_INFO;
	}

	@RequestMapping(value = "preadd", method = RequestMethod.GET)
	public String preAdd(HttpServletResponse response,
			HttpServletRequest request, ModelMap modelMap) {

		// Equipment equipment = equipmentService.getEquipment(equipmentId);
		//
		// String equipmentName = request.getParameter("equipmentName");
		// String equipmentKeywords = request.getParameter("equipmentKeywords");
		// String equipmentItemLevel =
		// request.getParameter("equipmentItemLevel");
		// String equipmentDescription = request
		// .getParameter("equipmentDescription");
		//
		// equipment.setEquipmentName(equipmentName);
		// equipment.setEquipmentDescription(equipmentDescription);
		// equipment.setEquipmentItemLevel(equipmentItemLevel);
		// equipment.setEquipmentKeywords(equipmentKeywords);
		//
		// equipmentService.updateEquipment(equipment);
		//
		// OperateInfo operateInfo = new OperateInfo();
		// operateInfo.setInfo(OPERATE_INFO_UPDATE_OK);
		// operateInfo.addLink(new Link(LINK_NAME_INDEX, LINK_INDEX));
		// modelMap.addAttribute(REQUEST_KEY_OPERATE_INFO, operateInfo);

		return RETURN_VIEW_PREFIX + VIEW_ADD;
	}

	@RequestMapping(value = "update/{equipmentId}", method = RequestMethod.POST)
	public String update(HttpServletResponse response,
			HttpServletRequest request, ModelMap modelMap,
			@PathVariable("equipmentId") String equipmentId) {

		Equipment equipment = equipmentService.getEquipment(equipmentId);

		String equipmentName = request.getParameter("equipmentName");
		String equipmentKeywords = request.getParameter("equipmentKeywords");
		String equipmentItemLevel = request.getParameter("equipmentItemLevel");
		String equipmentDescription = request
				.getParameter("equipmentDescription");

		equipment.setEquipmentName(equipmentName);
		equipment.setEquipmentDescription(equipmentDescription);
		equipment.setEquipmentItemLevel(equipmentItemLevel);
		equipment.setEquipmentKeywords(equipmentKeywords);

		equipmentService.updateEquipment(equipment);

		OperateInfo operateInfo = new OperateInfo();
		operateInfo.setInfo(OPERATE_INFO_UPDATE_OK);
		operateInfo.addLink(new Link(LINK_NAME_INDEX, LINK_INDEX));
		modelMap.addAttribute(REQUEST_KEY_OPERATE_INFO, operateInfo);

		return VIEW_OPERATE_INFO;
	}

	@Autowired
	private ISearchService searchService;

	public ISearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(ISearchService searchService) {
		this.searchService = searchService;
	}

	@RequestMapping(value = "search/{keyword}-{currentPage}-{rowSize}", method = RequestMethod.GET)
	public String result(ModelMap modelMap,
			@PathVariable("keyword") String keyword,
			@PathVariable("currentPage") Integer currentPage,
			@PathVariable("rowSize") Integer rowSize) throws Exception {
		if (keyword == null || keyword.trim().length() == 0) {
			return "redirect:/" + RETURN_VIEW_PREFIX + VIEW_INDEX;
		}

		IPaginationInfo pagination = new DefaultPaginationInfo();
		pagination.setCurrentPage(currentPage);
		pagination.setRowSize(rowSize);

		List<String> keywords = new ArrayList<String>();
		keywords.add(keyword);

		PaginationModel<List<Equipment>> paginationModel = searchService
				.searchEquipments(keywords, pagination);
		modelMap.addAttribute("keyword", keyword);

		modelMap.addAttribute("paginationModel", paginationModel);

		return RETURN_VIEW_PREFIX + "search/" + VIEW_LIST;
	}

	@RequestMapping(value = "ajaxdelete/{equipmentId}", method = {
			RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public String ajaxDelete(@PathVariable("equipmentId") String equipmentId,
			HttpServletResponse response, ModelMap modelMap) {
		JsonObject object = new JsonObject();
		Equipment matter = equipmentService.getEquipment(equipmentId);

		if (matter == null) {
			object.addProperty(CRUD_SUCCESS, false);
			object.addProperty(CRUD_INFO, "物品不存在");
		} else {
			try {
				equipmentService.deleteEquipment(matter);
				object.addProperty(CRUD_SUCCESS, true);
			} catch (Exception ex) {
				object.addProperty(CRUD_SUCCESS, false);
			}
		}

		return object.toString();
	}
}
